﻿using AutoMapper;
using MD5Hash;
using MediatR;
using RBAC.Domain;
using RBAC.Domain.Dto.Output;
using RBAC.ErrorCode;
using RBAC.Interstructrue.Base;
using RBAC.Read.Api.Application.Command.User.Login;

namespace RBAC.Read.Api.Application.Handler.User.Login
{
    public class LoginHandler : IRequestHandler<LoginCommand, APIResult<UserDto>>
    {
        private readonly IBaseRepository<UserModel> userRepository;
        private readonly IBaseRepository<RoleModel> roleRepository;
        private readonly IBaseRepository<UserRoleModel> userreoleRepository;
        private readonly IMapper mapper;
        private readonly ILogger<LoginHandler> logger;

        public LoginHandler(IBaseRepository<UserModel> userRepository, IBaseRepository<RoleModel> roleRepository, IBaseRepository<UserRoleModel> userreoleRepository, IMapper mapper, ILogger<LoginHandler> logger)
        {
            this.userRepository = userRepository;
            this.roleRepository = roleRepository;
            this.userreoleRepository = userreoleRepository;
            this.mapper = mapper;
            this.logger = logger;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task<APIResult<UserDto>> Handle(LoginCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDto> res = new APIResult<UserDto>();
            var pwd = request.Password.GetMD5();
            var user = userRepository.GetALL().FirstOrDefault(x => x.UserName == request.UserName && x.Password == pwd);
            if (user == null)
            {
                res.Code = APIEnums.Error;
                res.Msg = "用户名或密码错误";
                logger.LogError("用户名或密码错误");
                return Task.FromResult(res);
            }
            var userrole = userreoleRepository.GetALL().FirstOrDefault(x => x.UserId == user.Id);
            if (userrole == null)
            {
                res.Code = APIEnums.Error;
                res.Msg = "尚未为用户配置角色";
                res.Data = null;
                logger.LogError("尚未为用户配置角色");
                return Task.FromResult(res);
            }
            var role = roleRepository.GetModel(userrole.RoleId);
            if (role == null)
            {
                res.Code = APIEnums.Error;
                res.Msg = "用户角色不存在";
                res.Data = null;
                logger.LogError("用户角色不存在");
                return Task.FromResult(res);
            }
            var data=mapper.Map<UserDto>(user);
            data.RoleName = role.RoleName;
            data.RoleId = role.Id;
            res.Code = APIEnums.Success;
            res.Data = data;
            res.Msg = "用户登录成功";
            logger.LogInformation("用户登录成功");
            return Task.FromResult(res);
        }
    }
}
